package dao

import (
	"fmt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/os/gtime"
)

type t_alarm_now struct {
}

var T_alarm_now = t_alarm_now{}

func (a *t_alarm_now) GetList(where ...string) (list gdb.List, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_alarm_now")
	if len(where) == 0 {
	} else {
		model = model.Where(where[0])
	}
	res, err := model.All()
	return res.List(), err
}

func (a *t_alarm_now) Save(data interface{}) (isOk bool, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	_, err = db.Model("t_alarm_now").Data(data).Save()
	if err != nil {
		return false, err
	} else {
		return true, nil
	}
}

func (a *t_alarm_now) GetHappenAlarm(farmid string, houseid string, device_type string, device_addr string, alarm_content string) (item gdb.Map, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_alarm_now")
	res, error := model.Where(
		fmt.Sprintf(
			"farmid='%s' and houseid='%s' and device_type='%s' and device_addr='%s' and alarm_content='%s' and add_time>'%s' ",
			farmid,
			houseid,
			device_type,
			device_addr,
			alarm_content, gtime.Now().AddDate(0, -6, 0).String())).One()
	if error != nil {
		err = error
	} else {
		if res != nil {
			item = res.Map()
		}

	}

	return item, err
}

func (a *t_alarm_now) GetNodeHappenAlarm(device_addr string, sn string, alarm_content string) (item gdb.Map, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("t_alarm_now")
	res, error := model.Where(fmt.Sprintf("device_addr='%s' and sn='%s' and alarm_content='%s' and add_time>'%s' ", device_addr, sn, alarm_content, gtime.Now().AddDate(0, -6, 0).String())).One()
	if error != nil {
		err = error
	} else {
		if res != nil {
			item = res.Map()
		}
	}
	return item, err
}

func (a *t_alarm_now) AddAlarm(farmid interface{}, houseid interface{}, device_type string, device_addr string, sn string, level int, _type string, subtype string, alarm_content string, remark string) (isOk bool, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	now := gtime.Now()
	data := gdb.Map{
		"farmid":        farmid,
		"houseid":       houseid,
		"device_type":   device_type,
		"device_addr":   device_addr,
		"sn":            sn,
		"level":         level,
		"type":          _type,
		"subtype":       subtype,
		"alarm_content": alarm_content,
		"add_time":      now.String(),
		"add_time_ts":   now.TimestampMilli(),
		"remark":        remark,
	}
	_, err = db.Model("t_alarm_now").Data(data).Save()
	if err != nil {
		return false, err
	} else {
		return true, nil
	}
}

func (a *t_alarm_now) Delete(id string) (isOk bool, err error) {
	db := g.DB(g.Cfg().GetString("custom.db_name"))
	_, err = db.Model("t_alarm_now").Delete(fmt.Sprintf("id=%s", id))
	if err != nil {
		return false, err
	} else {
		return true, nil
	}
}
